package organization

import (
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/activity"
	"gq_volunteer_platform/model/organization"
	"gq_volunteer_platform/model/user"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {

	var req struct {
		Name string `binding:"max=255"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var list []struct {
		ID   uint
		Name string
	}

	var tx = bean.MysqlDb.Model(&organization.Organization{})

	if req.Name != "" {
		tx = tx.Where("`name` like ?", "%"+req.Name+"%")
	}

	// 查询列表
	if err := tx.Order("`sort` ASC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"list": list,
	})

}

func Detail(c *gin.Context) {

	var req struct {
		ID uint `binding:"max=10000000"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var detail struct {
		ID                     uint
		Name                   string
		ResponsiblePerson      string
		ResponsiblePersonPhone string
		Address                string
		Longitude              float64
		Latitude               float64
	}

	// 查询详情
	if err := bean.MysqlDb.Model(&organization.Organization{}).Where("`id`=?", req.ID).First(&detail).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询已审核用户总数
	var volunteer_count int64
	if err := bean.MysqlDb.Model(&user.User{}).Where("`organization_id`=? AND `check_status`=?", req.ID, "已审核").Count(&volunteer_count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询举办活动数
	var activity_count int64
	if err := bean.MysqlDb.Model(&activity.Activity{}).Where("`model_type`=?", "活动").Where("`organization_id`=? AND `status` IN ?", req.ID, []string{"招募中", "进行中", "已结束"}).Count(&activity_count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询已结束培训总数
	var train_count int64
	if err := bean.MysqlDb.Model(&activity.Activity{}).Where("`model_type`=?", "培训").Where("`organization_id`=? AND `status` IN ?", req.ID, []string{"招募中", "进行中", "已结束"}).Count(&train_count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"detail":          detail,
		"volunteer_count": volunteer_count,
		"activity_count":  activity_count,
		"train_count":     train_count,
	})

}
